import { ref } from "vue";
import { readToken, clearToken } from "@/state/token";

const userInfo = ref(fetchUserInfo());

function filterUserInfo(info) {
  if (info === null) {
    return null;
  }
  const username = info.username;
  if (typeof username != "string") {
    throw Error("Username is not string");
  }
  const userId = info.userId;
  if (typeof userId != "number") {
    throw Error("User ID is not a number");
  }
  const isAdmin = info.isAdmin;
  if (typeof isAdmin != "boolean") {
    throw Error("Invalid isAdmin");
  }
  return {
    username,
    userId,
    isAdmin
  };
}

function updateUserInfo(info) {
  const filteredInfo = filterUserInfo(info);
  localStorage.setItem("user", JSON.stringify(filteredInfo));
  userInfo.value = filteredInfo;
}

function fetchUserInfo() {
  if (readToken() === null) {
    return null;
  }
  const info = localStorage.getItem("user");
  if (info === null) {
    return null;
  }
  try {
    const infoObj = JSON.parse(info);
    return filterUserInfo(infoObj);
  } catch (_) {
    return null;
  }
}

function clearUserInfo() {
  localStorage.removeItem("user");
  clearToken();
  userInfo.value = null;
}

export { updateUserInfo, fetchUserInfo, clearUserInfo, userInfo };